package com.wen.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wen.mapper.ProductMapper;
import com.wen.pojo.CurrentUser;
import com.wen.pojo.InStore;
import com.wen.pojo.OutStore;
import com.wen.pojo.Product;
import com.wen.utils.PageBean;
import com.wen.utils.Result;
import com.wen.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.wen.mapper.OutStoreMapper;
import com.wen.service.OutStoreService;

import java.util.List;

@Service
public class OutStoreServiceImpl implements OutStoreService{

    @Autowired
    private OutStoreMapper outStoreMapper;

    @Override
    public Result addCk(OutStore outStore) {
        CurrentUser currentUser = ThreadLocalUtil.get();
        int userId = currentUser.getUserId();
        outStore.setCreateBy(userId);
        int i = outStoreMapper.addCk(outStore);
        if(i>0){
            return Result.ok(200,"出库单生成成功",null);
        }else{
            return Result.fail(1,"出库单生成失败");
        }
    }

    @Override
    public PageBean<OutStore> allList(Integer pageNum, Integer pageSize, OutStore outStore) {
        PageBean<OutStore> pb = new PageBean<>();
        PageHelper.startPage(pageNum,pageSize);
        List<OutStore> outStores = outStoreMapper.allOutList(outStore);
        Page<OutStore> p = (Page<OutStore>) outStores;
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());
        return pb;
    }

    @Override
    public Result outStore(OutStore outStore) {
        Product p  = new Product();
        p.setProductId(outStore.getProductId());
        p.setOutNum(outStore.getOutNum());
        Product products = outStoreMapper.findById(outStore.getProductId());
        Integer kc = products.getProductInvent();
        if(outStore.getOutNum() > kc){
            return Result.fail(1,"库存不足");
        }
        int i = outStoreMapper.updIsOut(outStore);
        if(i>0){
            outStoreMapper.updKc(p);
            return Result.ok(200,"成功",null);
        }else{
            return Result.fail(1,"失败");
        }
    }
}
